<template>
  <div class="container">
    <div class="head">
      <!-- 筛选栏 -->
      <a-form
        ref="formRef"
        :model="formState"
        layout="inline"
        :label-col="{ style: { width: '80px' } }"
        AutoComplete="off"
      >
        <a-form-item label="项目名称" name="projectName">
          <a-input
            v-model:value="formState.projectName"
            placeholder="输入项目名称"
            style="width: 200px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="项目状态" name="projectStatus">
          <a-select
            ref="select"
            v-model:value="formState.projectStatus"
            style="width: 150px"
            placeholder="筛选状态"
            :options="statusOptions"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="searchProjects">
            <template #icon><search-outlined /></template>查询
          </a-button>
          <a-button style="margin-left: 8px" @click="resetForm">
            <template #icon><redo-outlined /></template>重置
          </a-button>
        </a-form-item>
      </a-form>

      <div>
        <a-button type="primary" @click="showAddProjectModal">
          <template #icon><plus-outlined /></template>添加项目
        </a-button>
      </div>
    </div>

    <div class="body">
      <a-table
        :columns="columns"
        :bordered="true"
        :data-source="data"
        :pagination="false"
        row-key="projectId"
        :loading="loading"
        :scroll="{ y: '65vh' }"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'projectName'">
            <a @click="viewProjectDetail(record)">{{ text }}</a>
          </template>
          <template v-else-if="column.dataIndex === 'projectStatus'">
            <span v-if="text == 1"><a-tag color="blue">未进行</a-tag></span>
            <span v-else-if="text == 2"><a-tag color="green">进行中</a-tag></span>
            <span v-else-if="text == 3"><a-tag color="orange">已暂停</a-tag></span>
            <span v-else-if="text == 4"><a-tag color="gray">已结案</a-tag></span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space>
              <a @click="viewProjectDetail(record)">查看</a>
              <a @click="editProject(record)">编辑</a>
              <a-popconfirm
                title="确定要移除这个项目吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="removeProject(record)"
              >
                <a style="color: #ff4d4f">移除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <a-pagination
        class="pagination-container"
        v-model:current="current"
        v-model:page-size="pageSizeRef"
        :total="total"
        show-size-changer
        @change="handlePageChange"
      />
    </div>
  </div>

  <!-- 添加项目弹窗 -->
  <a-modal
    v-model:visible="addProjectModalVisible"
    title="添加项目到课程"
    width="600px"
    :maskClosable="false"
    :destroyOnClose="true"
    @ok="confirmAddProject"
  >
    <a-form :model="addProjectForm" layout="vertical">
      <!-- 项目选择 -->
      <a-form-item label="选择已有项目">
        <a-select
          v-model:value="addProjectForm.selectedProjects"
          mode="multiple"
          placeholder="请选择项目"
          style="width: 100%"
          :options="availableProjects"
          :fieldNames="{ label: 'projectName', value: 'projectId' }"
        >
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useStore } from 'vuex';
import { message } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { SearchOutlined, RedoOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import CourseDao from '@/daos/course_dao';
import ProjectDao from '@/daos/project_dao';

const router = useRouter();
const store = useStore();
const courseDao = new CourseDao();
const projectDao = new ProjectDao();

// 表单状态和引用
const formRef = ref();
const formState = reactive({
  projectName: '',
  projectStatus: undefined,
  courseId: store.getters.courseId
});

// 项目状态选项
const statusOptions = [
  { value: 1, label: '未进行' },
  { value: 2, label: '进行中' },
  { value: 3, label: '已暂停' },
  { value: 4, label: '已结案' }
];

// 表格数据和加载状态
const data = ref([]);
const loading = ref(true);
const current = ref(1);
const pageSizeRef = ref(10);
const total = ref(0);

// 添加项目相关状态
const addProjectModalVisible = ref(false);
const addProjectForm = reactive({
  selectedProjects: []
});
const availableProjects = ref([]);

// 表格列定义
const columns = [
  { title: '项目名称', dataIndex: 'projectName', key: 'projectName', width: 200 },
  { title: '项目描述', dataIndex: 'projectDescription', key: 'projectDescription', width: 300 },
  { title: '项目状态', dataIndex: 'projectStatus', key: 'projectStatus', width: 120, align: 'center' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180, align: 'center' },
  { title: '操作', dataIndex: 'action', key: 'action', width: 150, align: 'center', fixed: 'right' }
];

// 获取课程关联的项目
const fetchCourseProjects = async () => {
  loading.value = true;
  try {
    const result = await courseDao.findCourseProjects(
      formState.courseId,
      formState.projectName,
      formState.projectStatus,
      current.value - 1,
      pageSizeRef.value
    );
    
    if (result.data.code === 200) {
      data.value = result.data.data.rows;
      total.value = result.data.data.totalCount;
    } else {
      message.error(result.data.msg || '获取项目列表失败');
    }
  } catch (error) {
    console.error('获取课程项目列表失败:', error);
    message.error('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};

// 查询项目
const searchProjects = () => {
  current.value = 1;
  fetchCourseProjects();
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  searchProjects();
};

// 分页变化处理
const handlePageChange = (page) => {
  current.value = page;
  fetchCourseProjects();
};

// 查看项目详情
const viewProjectDetail = (record) => {
  store.commit('project/SET_PROJECTID', record.projectId);
  store.commit('project/SET_PROJECTNAME', record.projectName);
  store.commit('project/SET_PROJECTTYPE', record.projectType);
  router.push({ 
    name: '项目详情', 
    params: { projectId: record.projectId }
  });
};

// 编辑项目
const editProject = (record) => {
  // 这里可以实现编辑项目的逻辑，例如打开编辑弹窗
  message.info('编辑项目: ' + record.projectName);
};

// 移除项目
const removeProject = async (record) => {
  try {
    loading.value = true;
    const result = await courseDao.removeCourseProject(formState.courseId, record.projectId);
    
    if (result.data.code === 200) {
      message.success('项目已从课程移除');
      fetchCourseProjects();
    } else {
      message.error(result.data.msg || '移除项目失败');
    }
  } catch (error) {
    console.error('移除项目失败:', error);
    message.error('移除项目失败');
  } finally {
    loading.value = false;
  }
};

// 显示添加项目弹窗
const showAddProjectModal = async () => {
  try {
    const userId = store.getters.userId || store.getters['user/userId'];
    const result = await projectDao.getAvailableProjects(formState.courseId, userId);
    
    if (result.data.code === 200) {
      availableProjects.value = result.data.data;
      addProjectModalVisible.value = true;
    } else {
      message.error(result.data.msg || '获取可添加的项目失败');
    }
  } catch (error) {
    console.error('获取可添加项目失败:', error);
    message.error('获取可添加项目失败');
  }
};

// 确认添加项目
const confirmAddProject = async () => {
  if (!addProjectForm.selectedProjects || !addProjectForm.selectedProjects.length) {
    message.warning('请选择要添加的项目');
    return;
  }
  
  try {
    loading.value = true;
    const result = await courseDao.addProjectsToCourse(
      formState.courseId, 
      addProjectForm.selectedProjects
    );
    
    if (result.data.code === 200) {
      message.success('项目已添加到课程');
      addProjectModalVisible.value = false;
      // 清空选择项
      addProjectForm.selectedProjects = [];
      // 刷新项目列表
      fetchCourseProjects();
    } else {
      message.error(result.data.msg || '添加项目失败');
    }
  } catch (error) {
    console.error('添加项目失败:', error);
    message.error('添加项目失败');
  } finally {
    loading.value = false;
  }
};

// 页面挂载完毕后调用方法获取项目内容
onMounted(() => {
  // 清空选择项
  addProjectForm.selectedProjects = [];
  // 获取课程ID
  formState.courseId = store.getters.courseId || Number(router.currentRoute.value.params.courseId);
  // 获取项目列表
  fetchCourseProjects();
});
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  padding: 1%;
  height: 100%;
  min-width: 1280px;
  overflow: auto;
}
.head {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 15px;
  margin-bottom: 1%;
  height: 10%;
  width: 100%;
  min-height: 75px;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid lightgray;
  border-radius: 10px;
  background-color: #fff;
  overflow: auto;
}

.body {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0.5%;
  height: 90%;
  width: 100%;
  min-height: 540px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid lightgray;
  border-radius: 10px;
  background-color: #fff;
  overflow: auto;
}

.ant-table-wrapper {
  position: relative;
  height: 100%;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}
</style> 